<?php

require('util.php');

while (1) {
    $redis = new Redis();
    $redis->connect('sh-crs-r28csn61.sql.tencentcdb.com', 25772);
    $redis->auth('Lx231404');

    //检测是否有任务
    // $newSerial = $redis->get('ti_worker_order');
    // if (empty($newSerial)) {
    //     logger('无任务...');
    //     sleep(3);
    //     continue;
    // }

    $cookie = $redis->get('ti_worker_cookie');
    $redis->close();
    if (empty($cookie)) {
        logger("从redis读取cookie失败");
        sleep(3);
        continue;
    }


    //在第3步，获取CSRFToken
    $url = 'https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/regulations-step/choose';
    [$header, $res] = getUrl($url, [
        'Cookie: '.$cookie,
        'Referer: https://www.ti.com.cn/store/ti/zh/checkout/multi/cn-tax-invoice',
    ]);
    $found = 0;
    if (strpos($res, 'ACC.config.CSRFToken') !== false && preg_match('|ACC.config.CSRFToken = "([0-9a-zA-Z-]+)"|i', $res, $matches) && !empty($matches) && !empty($matches[1])) {
        $found = 1;
        $CSRFToken = $matches[1];
    }
    if ($found) {
        logger('获取CSRFToken成功,'.$CSRFToken);
    } else {
        logger("获取CSRFToken失败！\n".$res);
        sleep(3);
        continue;
    }
    //$CSRFToken = 'b9812d3e-c167-400a-82a0-e19b20b1fba0';
    //exit('token:'.$CSRFToken);


    //合规确认
    $getData = http_build_query([
        'militaryFlag' => 'No',
        'eeId' => 1090,
        'eeName' => '单板计算机',
        'appId' => 892,
        'appName' => '工厂自动化与控制',
        'selectedIOR' => '',
    ]);
    $url = 'https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/regulations-step/validate?'.$getData;
    [$header, $res] = getUrl($url, [
        'Cookie: '.$cookie,
        'Referer: https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/regulations-step/choose',
    ]);
    logger("合规确认:\n".print_r($header, true)."\n".print_r($res, true)."\n\n");


    //确认运费
    $url = 'https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/delivery-method/select?delivery_method=v2-china-DOM-0_1k-EH&termsAccepted=Yes';
    [$header, $res] = getUrl($url, [
        'Cookie: '.$cookie,
        'Referer: https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/delivery-method/choose',
    ]);
    logger("运费确认:\n".print_r($header, true)."\n".print_r($res, true)."\n\n");


    //提交订单
    $url = 'https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/payment-method/citcon/addSelectedPayment';
    $postData = 'paymentMethod=unionpay_b&CSRFToken='.$CSRFToken;
    [$header, $res] = postUrl($url, $postData, [
        'Cookie: '.$cookie,
        'Referer: https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/payment-method/add',
    ]);
    //检查是否成功
    $found = 0;
    if (strpos($res, '您的订单号是') !== false) {
        $found = 1;
    }
    if ($found) {
        $msg = '下单成功';
        logger($msg);
        easyPushWechatMsg($msg);
    } else {
        $msg = "下单失败\n".print_r($res, true);
        logger($msg);
        easyPushWechatMsg('下单失败');
    }
    sleep(20);
}


